package com.longrise.co.ui.carfiles.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.longrise.co.R;
import com.longrise.co.ui.carfiles.adapter.RepairDetailAdapter;
import com.longrise.co.ui.carfiles.contract.CarFilesContract;
import com.longrise.co.ui.carfiles.model.CarFilesModel;
import com.longrise.co.ui.carfiles.model.ItemRepairDetailEntity;
import com.longrise.co.ui.carfiles.model.ItemTitleBean;
import com.longrise.co.ui.carfiles.model.RepairRecordDetail;
import com.longrise.co.ui.carfiles.presenter.CarFilesPresenter;
import com.longrise.co.utils.Constants;
import com.longrise.co.utils.StringUtils;
import com.ly.common.base.BaseFragment;
import com.ly.common.commonutils.TimeUtil;
import com.ly.common.dialog.DialogOnClickListener;
import com.ly.common.dialog.MDAlertDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import longrise.phone.com.baidulib.baidu.MapNavUtils;

import static com.longrise.co.utils.Constants.REPAIR_DETAIL_TYPE_THREE;

/**
 * Created by luoyang on 2017-7-19.
 */

public class RepairDetailFragment extends BaseFragment<CarFilesPresenter, CarFilesModel> implements CarFilesContract.View<RepairRecordDetail>, View.OnClickListener, BaseQuickAdapter.OnRecyclerViewItemClickListener, DialogOnClickListener {

    @Bind(R.id.head_title)
    TextView headTitle;
    @Bind(R.id.detail_content)
    RecyclerView mRecyclerView;
    @Bind(R.id.complaint_name)
    TextView complaintName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;

    TextView locationTv;
    TextView callTv;
    TextView carNoValue;
    TextView detailDate;
    TextView detailNum;
    TextView detailPrice;
    TextView detailMile;
    TextView detailRepairType;
    TextView detailDesc;
    TextView detailReason;

    TextView detailVin;

    private ImageView mCallIv;
    private ImageView mLocationIv;

    private TextView warrantyInformation, complaintTv, evaluationTv;

    private RepairDetailAdapter mAdapter;

    private String mRecordId;
    private String mYear;
    private String mCarNo;
    private boolean mIsComplaint;
    private boolean mIsEvaluation;

    private View mHeadView, mFootView;

    private RepairRecordDetail mData;

    private MDAlertDialog mCallDialog;

    private MapNavUtils mapNavUtils;


    @Override
    protected int getLayoutResource() {
        return R.layout.fg_repair_detail;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        setText(headTitle, "维修详情");
        mRecordId = getArguments().getString("recordId");
        mYear = getArguments().getString("year");
        mCarNo = getArguments().getString("carNo");
        mIsComplaint = getArguments().getBoolean("isComplaint");
        mIsEvaluation = getArguments().getBoolean("isEvaluation");

        initRecyclerView();
        initHeadOrFootView();
        mPresenter.repairRecordDetailRequest(mRecordId, mYear, mCarNo);
        mapNavUtils = new MapNavUtils(getActivity());
    }

    private void initHeadOrFootView() {
        mHeadView = LayoutInflater.from(getContext()).inflate(R.layout.fg_repair_detail_header, null);
        mFootView = LayoutInflater.from(getContext()).inflate(R.layout.fg_repair_detail_footer, null);
        //地址
        locationTv = (TextView) mHeadView.findViewById(R.id.location_tv);
        //导航
        mLocationIv = (ImageView)mHeadView.findViewById(R.id.complaint_location_iv);
        //电话
        callTv = (TextView) mHeadView.findViewById(R.id.call_tv);
        //车牌号码
        carNoValue = (TextView) mHeadView.findViewById(R.id.car_no_value);
        //结算日期
        detailDate = (TextView) mHeadView.findViewById(R.id.detail_date);
        //结算编号
        detailNum = (TextView) mHeadView.findViewById(R.id.detail_num);
        //维修费用
        detailPrice = (TextView) mHeadView.findViewById(R.id.detail_price);
        //送修里程
        detailMile = (TextView) mHeadView.findViewById(R.id.detail_mile);
        //维修类别
        detailRepairType = (TextView) mHeadView.findViewById(R.id.detail_repair_type);
        //故障描述
        detailDesc = (TextView) mHeadView.findViewById(R.id.detail_desc);
        //故障原因
        detailReason = (TextView) mHeadView.findViewById(R.id.detail_reason);

        //质保信息
        warrantyInformation = (TextView) mFootView.findViewById(R.id.warranty_information);
        //投诉按钮
        complaintTv = (TextView) mFootView.findViewById(R.id.complaint_tv);
        //评价按钮
        evaluationTv = (TextView) mFootView.findViewById(R.id.evaluation_tv);
        //电话
        mCallIv = (ImageView) mHeadView.findViewById(R.id.complaint_call_iv);

        detailVin = (TextView) mHeadView.findViewById(R.id.detail_vin);

        complaintTv.setOnClickListener(this);
        evaluationTv.setOnClickListener(this);
        mCallIv.setOnClickListener(this);
        mLocationIv.setOnClickListener(this);
    }

    @Override
    public void requestSuccess(RepairRecordDetail bean) {
        if(bean == null) {
            return ;
        }
        mData = bean;
        setText(complaintName, bean.getCompanyname());

        if(!StringUtils.isEmpty(bean.getStar())) {
            ratingBar.setRating(Float.parseFloat(bean.getStar()));
        }

        setText(locationTv, bean.getCompanyaddress());
        setText(callTv, bean.getBusphone());
        setText(carNoValue, bean.getCarno());
        setText(detailDate, TimeUtil.getDateYMD(bean.getSettledate()));
        setText(detailNum, bean.getSettleno());
        setText(detailPrice, bean.getTotal());
        if(bean.getRepairmile()!=null)
        setText(detailMile,  bean.getRepairmile() +"(公里)");
        setText(detailRepairType, bean.getRepairtype());
        setText(detailDesc, bean.getFaultdescript());
//        setText(detailReason, bean.getFaultreason());
        setText(warrantyInformation, bean.getWarrantymsg());
        setText(detailVin, bean.getCarvin());

        complaintTv.setText(mIsComplaint ? "已投诉" : "投诉");
        evaluationTv.setText(mIsEvaluation ? "已评价" : "评价");

        mAdapter.addHeaderView(mHeadView);
        mAdapter.addFooterView(mFootView);

        setItem(bean);
    }

    private void setItem(RepairRecordDetail bean) {
        List<ItemRepairDetailEntity> listAll = new ArrayList<>();
        listAll.add(new ItemRepairDetailEntity(Constants.REPAIR_DETAIL_TYPE_ONE, new ItemTitleBean("维修项目")));
        if(bean != null) {
            if (bean.getLciptimesheet() != null && bean.getLciptimesheet().size() > 0) {
                addProjectData(listAll, bean.getLciptimesheet());
            }
        }
        listAll.add(new ItemRepairDetailEntity(Constants.REPAIR_DETAIL_TYPE_ONE, new ItemTitleBean("维修配件")));
        if(bean != null) {
            if (bean.getLcipmaterials() != null && bean.getLcipmaterials().size() > 0) {
                addPartsData(listAll, bean.getLcipmaterials());
            }
        }
        mAdapter.setNewData(listAll);
    }

    private void addProjectData(List<ItemRepairDetailEntity> entityList, List<RepairRecordDetail.LciptimesheetBean> projectDatas) {
       /* *//**
         * laborhourprice :
         * repairhours :
         * repaircost :
         * repairproject : 左侧前后门，前后叶，前后保钣金修复油漆
         * workinghours : 300.00
         * repairname :
         *//*
        RepairRecordDetail.LciptimesheetBean bean = new RepairRecordDetail.LciptimesheetBean();
        bean.setRepairname("名称");
        bean.setRepairproject("项目");
        bean.setLaborhourprice("工时单价\n（元/时）");
        bean.setRepaircost("工时费用\n（元）");
        bean.setRepairhours("工时\n（时）");
        bean.setWorkinghours("总耗时\n（时）");
        entityList.add(new ItemRepairDetailEntity(REPAIR_DETAIL_TYPE_THREE, bean));*/
        for(RepairRecordDetail.LciptimesheetBean b : projectDatas) {
            entityList.add(new ItemRepairDetailEntity(REPAIR_DETAIL_TYPE_THREE, b));
        }
    }

    private void addPartsData(List<ItemRepairDetailEntity> entityList, List<RepairRecordDetail.LcipmaterialsBean> partDatas) {
       /* *//**
         * partscode : TEMP_PARTS
         * partscost :
         * partsattribute :
         * partsquantity : 1.00
         * partsname : 后门密封条
         * partsallcost :
         * partsno :
         *//*
        RepairRecordDetail.LcipmaterialsBean bean = new RepairRecordDetail.LcipmaterialsBean();
        bean.setPartsname("名称");
        bean.setPartscode("编码");
        bean.setPartscost("单价\n（元）");
        bean.setPartsquantity("数量");
        bean.setPartsallcost("费用\n（元）");
        bean.setPartsattribute("属性");
        entityList.add(new ItemRepairDetailEntity(Constants.REPAIR_DETAIL_TYPE_TWO, bean));*/
        for(RepairRecordDetail.LcipmaterialsBean b : partDatas) {
            entityList.add(new ItemRepairDetailEntity(Constants.REPAIR_DETAIL_TYPE_TWO, b));
        }
    }

    @Override
    public void onComplete() {

    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new RepairDetailAdapter(null);

        mAdapter.openLoadMore(false);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    public static RepairDetailFragment newInstance(String recordId, String year, String carNo, boolean isComplaint, boolean isEvaluation) {

        Bundle args = new Bundle();
        args.putString("recordId", recordId);
        args.putString("year", year);
        args.putString("carNo", carNo);
        args.putBoolean("isComplaint", isComplaint);
        args.putBoolean("isEvaluation", isEvaluation);
        RepairDetailFragment fragment = new RepairDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void initCallDialog() {
        mCallDialog = new MDAlertDialog.Builder(getContext())
                .setContentText("确定拨打该企业电话？")
                .setOnclickListener(this)
                .build();
    }


    @OnClick({R.id.head_back})
    public void onViewClicked(View view) {
        if(checkDoubleClick()) {
            switch (view.getId()) {
                case R.id.head_back :
                    _mActivity.onBackPressed();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        if(mData!=null) {
            if (v.getId() == R.id.complaint_tv) {
                if (mIsComplaint) {
                    showErrorTip("已投诉该企业，不可重复投诉");
                    return;
                }
                //投诉
                start(RepairComplaintFragment.newInstance(mData.getCompanyid(), mRecordId, mYear, null));
            } else if (v.getId() == R.id.evaluation_tv) {
                if (mIsEvaluation) {
                    showErrorTip("已评价这次维修服务，不可重复评价");
                    return;
                }
                //评价
                start(RepairEvaluationFragment.newInstance(mData.getCompanyid(), mRecordId, mData.getYears()));
            } else if (v.getId() == R.id.complaint_call_iv) {
                if (StringUtils.isEmpty(mData.getBusphone())) {
                    showLongToast("未填写电话信息，无法进行此操作");
                    return;
                }
                if (mCallDialog == null) {
                    initCallDialog();
                }
                mCallDialog.show();
            } else if(v.getId() == R.id.complaint_location_iv){
                if(!StringUtils.isEmpty(mData.getAreaid())&&!StringUtils.isEmpty(mData.getCompanyid())){
                    mapNavUtils.start(0.0,0.0,mData.getCompanyaddress());
                }else{
                    showLongToast("地址信息有误");
                }
            }
        }
    }


    @Override
    public void onItemClick(View view, int i) {
        if(i >= 0 && i < mAdapter.getData().size()) {
            ItemRepairDetailEntity bean = (ItemRepairDetailEntity)mAdapter.getData().get(i);
            List<ItemRepairDetailEntity> newList = new ArrayList<>();

            if(bean != null && Constants.REPAIR_DETAIL_TYPE_ONE == bean.getItemType()) {
                ItemTitleBean titleBean = (ItemTitleBean)bean.getObj();
                boolean isEx = !titleBean.isExpansion();
                titleBean.setExpansion(isEx);

                for(int j=0; j< mAdapter.getData().size() ;j++) {
                    ItemRepairDetailEntity ide = (ItemRepairDetailEntity)mAdapter.getData().get(j);
                    if(Constants.REPAIR_DETAIL_TYPE_ONE == ide.getItemType()) {
                        ItemTitleBean ttb = (ItemTitleBean)ide.getObj();
                        newList.add(ide);
                        if(ttb.isExpansion()) {
                            if(mData!=null) {
                                if ("维修项目".equals(ttb.getName())) {
                                    addProjectData(newList, mData.getLciptimesheet());
                                } else if ("维修配件".equals(ttb.getName())) {
                                    addPartsData(newList, mData.getLcipmaterials());
                                }
                            }
                        }

                    }
                }
                mAdapter.setNewData(newList);
            }


        }

    }

    @Override
    public void clickLeftButton(View view) {
        if(mCallDialog != null) {
            mCallDialog.dismiss();
        }
    }

    @Override
    public void clickRightButton(View view) {
        //拨打电话
        if(mData != null && !StringUtils.isEmpty(mData.getBusphone())) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + mData.getBusphone()));
            startActivity(intent);
        }

        if(mCallDialog != null) {
            mCallDialog.dismiss();
        }
    }

    @Override
    public void showErrorTip(String msg) {
        if(msg.contains("a null object reference")){
            complaintName.setVisibility(View.GONE);
            mAdapter.addHeaderView(mHeadView);
            mAdapter.addFooterView(mFootView);
            setItem(null);
        }else{
        super.showErrorTip(msg);
        }
    }
}
